Given that interfaces are valid .NET types, you may construct methods that take interfaces as parameters, as illustrated by the CloneMe() method earlier in this chapter. For the current example, assume you have defined another interface named IDraw3D:
// Models the ability to render a type in stunning 3D. public interface IDraw3D { void Draw3D(); }
Next, assume that two of your three shapes (ThreeDCircle and Hexagon) have been configured to support this new behavior:
// Circle supports IDraw3D. class ThreeDCircle : Circle, IDraw3D { ... public void Draw3D() { Console.WriteLine("Drawing Circle in 3D!"); } } // Hexagon supports IPointy and IDraw3D. class Hexagon : Shape, IPointy, IDraw3D { ... public void Draw3D() { Console.WriteLine("Drawing Hexagon in 3D!"); } }
Figure 9-3 presents the updated Visual Studio 2010 class diagram.
Figure 9-3. The updated shapes hierarchy
If you now define a method taking an IDraw3D interface as a parameter, you can effectively send in any object implementing IDraw3D. (If you attempt to pass in a type not supporting the necessary interface, you receive a compile-time error.) Consider the following method defined within your Program class:
// I'll draw anyone supporting IDraw3D. static void DrawIn3D(IDraw3D itf3d) { Console.WriteLine("-> Drawing IDraw3D compatible type"); itf3d.Draw3D(); }
We could now test whether an item in the Shape array supports this new interface, and if so, pass it into the DrawIn3D() method for processing:
static void Main(string[] args) { Console.WriteLine("***** Fun with Interfaces *****\n"); Shape[] myShapes = { new Hexagon(), new Circle(), new Triangle(), new Circle("JoJo") } ; for(int i = 0; i < myShapes.Length; i++) { ... // Can I draw you in 3D? if(myShapes[i] is IDraw3D) DrawIn3D((IDraw3D)myShapes[i]); } }
Here is the output of the updated application. Notice that only the Hexagon object prints out in 3D, as the other members of the Shape array do not implement the IDraw3D interface.
***** Fun with Interfaces ***** Drawing NoName the Hexagon -> Points: 6 -> Drawing IDraw3D compatible type Drawing Hexagon in 3D! Drawing NoName the Circle -> NoName's not pointy! Drawing Joe the Triangle -> Points: 3 Drawing JoJo the Circle -> JoJo's not pointy!